package main

import (
	"fmt"
	"net/http"

	"gin-learn/009-jwt-middleware/jwtUtil"

	"github.com/gin-gonic/gin"
)

func main() {

	engine := gin.Default()
	// VerifyCustomerToken 验证客户的token的中间件
	engine.Use(func(context *gin.Context) {
		if context.Request.RequestURI == "/login" {
			context.Next()
		} else {
			if token, ok := context.Request.Header["X-Token"]; ok {
				MapCalim, err := jwtUtil.VerifyToken(token[0])
				if err != nil {
					fmt.Printf("verify err=%v\n", err)
					context.Abort()
					context.JSON(http.StatusForbidden, gin.H{
						"err msg": err.Error(),
					})
				} else {
					// 判断username 是否为Damon
					if "Damon" != (*MapCalim)["username"] {
						context.Abort()
						context.JSON(http.StatusForbidden, gin.H{
							"err msg": "username is not Damon",
						})
					}
					fmt.Printf("verify success=%v\n", MapCalim)
					// token 校验成功
					context.Next()
				}
			} else {
				fmt.Println("miss header token")
				context.Abort()
				context.JSON(http.StatusForbidden, gin.H{
					"msg": "miss header token",
				})
			}
		}
	})

	engine.POST("/login", func(c *gin.Context) {
		user := c.PostForm("username")

		if user == "" {
			c.JSON(http.StatusBadRequest, gin.H{
				"msg": "username is empty",
			})
			return
		}
		token := jwtUtil.GetToken(user)
		c.JSON(http.StatusOK, gin.H{
			"token": token,
			"msg":   "ok",
		})
	})
	engine.POST("/doBusiness", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{
			"msg": "doBusiness",
		})
	})
	engine.Run(":9001")
}
